package hhm.wcnmd.web.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import hhm.wcnmd.core.exec.WcnmdProxy;
import hhm.wcnmd.core.model.CmdResponse;
import hhm.wcnmd.core.model.ConnectResponse;
import hhm.wcnmd.web.utils.RequestUtils;

@Controller
public class CmdController {

	@RequestMapping(value = "/wcnmd/connect", method = RequestMethod.POST)
	@ResponseBody
	public String connect(@RequestBody Map<String, String> map, HttpServletRequest req) {
		ConnectResponse response = new ConnectResponse();
		String requestIp = RequestUtils.getIpAddr(req);
		// 创建一个token
		String token = requestIp + System.currentTimeMillis();
		WcnmdProxy wcnmdProxy = new WcnmdProxy(token);
		response = wcnmdProxy.connect(map);
		return JSONObject.toJSONString(response);

	}

	@RequestMapping(value = "/wcnmd/disconnect", method = RequestMethod.POST)
	@ResponseBody
	public String disconnect(@RequestBody Map<String, String> map) {

		String token = map.get("connectToken");
		CmdResponse response = new CmdResponse();
		WcnmdProxy wcnmdProxy = new WcnmdProxy(token);
		response = wcnmdProxy.disconnect();
		return JSONObject.toJSONString(response);

	}

	@RequestMapping(value = "/wcnmd/execCmd", method = RequestMethod.POST)
	@ResponseBody
	public String execCmd(@RequestBody Map<String, String> map) {
		CmdResponse response = new CmdResponse();

		String cmdStr = map.get("cmd");
		String token = map.get("connectToken");
		// 拿到cmdStr后
		WcnmdProxy wcnmdProxy = new WcnmdProxy(token);
		response = wcnmdProxy.exec(cmdStr);
		return JSONObject.toJSONString(response);

	}

}
